package org.example.bucket;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class FlinkFixedBucketTable {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setString(RestOptions.BIND_PORT,"8081");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(conf);
        env.setParallelism(1);
        env.enableCheckpointing(5000, CheckpointingMode.EXACTLY_ONCE);
        TableEnvironment tableEnv = StreamTableEnvironment.create(env);

        tableEnv.executeSql("CREATE CATALOG paimon WITH (\n" +
                "    'type' = 'paimon',\n" +
                "    'warehouse' = 'file:///tmp/paimon'\n" +
                ");\n");

        tableEnv.executeSql("-- 创建datagen用于生成数据\n" +
                "CREATE TABLE behavior_gen (\n" +
                "    user_id STRING,\n" +
                "    item_id STRING,\n" +
                "    behavior BIGINT,\n" +
                "    dt AS '2025-01-09',\n" +
                "    eventtime TIMESTAMP_LTZ(3)\n" +
                ") WITH (\n" +
                "  'connector' = 'datagen'\n" +
                "  , 'rows-per-second' = '10'\n" +
                ");");

        tableEnv.executeSql("drop table if exists `paimon`.`default`.`user_behavior`");

        tableEnv.executeSql("CREATE TABLE IF NOT EXISTS `paimon`.`default`.`user_behavior`\n" +
                "(\n" +
                "    user_id STRING,\n" +
                "    item_id STRING,\n" +
                "    behavior BIGINT,\n" +
                "    dt STRING,\n" +
                "    eventtime TIMESTAMP_LTZ(3),\n" +
                "    WATERMARK FOR eventtime AS eventtime - INTERVAL '5' SECOND,\n" +
                "    PRIMARY KEY (dt, user_id) NOT ENFORCED\n" +
                ")\n" +
                "PARTITIONED BY (dt)\n" +
                "WITH (\n" +
                "    'partition.expiration-time' = '99999 d',\n" +
                "    'bucket' = '10',\n" +
                "    'bucket-key' = 'user_id',\n" +
                "    'sink.parallelism' = '10'" +
                ")\n" +
                ";");

        tableEnv.executeSql(
                "-- 插入数据\n" +
                        "INSERT INTO `paimon`.`default`.`user_behavior`\n" +
                        "SELECT\n" +
                        "    user_id\n" +
                        "    , item_id\n" +
                        "    , behavior\n" +
                        "    , dt\n" +
                        "    , eventtime\n" +
                        "FROM \n" +
                        "    behavior_gen\n" +
                        ";"
        );
    }
}
